/*
MIT License

Copyright (c) 2007 Ralf Kornmann

All right reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/

#include "stdafx.h"
#include "FunctionHook.h"
#include "Host.h"
#include "ASMInstruction.h"

const DWORD PatchSize = 5; // JMP + Addr

CFunctionHook::CFunctionHook (CHost& rHost, LPCWSTR strModule, LPCSTR strProc, DWORD Flags, FARPROC TargetProc)
	: m_RefCount (0)
	, m_rHost (rHost)
	, m_IsHooked (false)
	, m_strModule (strModule)
	, m_strProc (strProc)
	, m_Flags (Flags)
	, m_TargetProc (TargetProc)
	, m_hModule (NULL)
	, m_OrgProc (NULL)
	, m_PatchProc (NULL)
	, m_OrginalCodeSize (0)
	, m_pOriginalCode (NULL)
{
	if ((m_Flags & UAH_HOOK_FLAG_LOAD) == UAH_HOOK_FLAG_LOAD)
		m_hModule =	LoadLibraryW (strModule);
	else
		m_hModule = GetModuleHandle (strModule);

	if (m_hModule != NULL)
		m_OrgProc = GetProcAddress (m_hModule, strProc);

	HookFunction ();
}

CFunctionHook::~CFunctionHook ()
{
	if ((m_Flags & UAH_HOOK_FLAG_MONITOR) == UAH_HOOK_FLAG_MONITOR)
		m_rHost.RemoveMonitor (this);

	UnhookFunction ();

	if ((m_Flags & UAH_HOOK_FLAG_LOAD) == UAH_HOOK_FLAG_LOAD && m_hModule != NULL)
		FreeLibrary (m_hModule);
}

HRESULT STDMETHODCALLTYPE CFunctionHook::QueryInterface(REFIID riid, void **ppvObject)
{
	if (ppvObject == NULL)
		return E_POINTER;

	if (memcmp (&riid, &__uuidof(IUnknown), sizeof(GUID)) == 0)
		*ppvObject = (IUnknown*)this;
	else if (memcmp (&riid, &__uuidof(IUAHHockedFunction), sizeof(GUID)) == 0)
		*ppvObject = (IUAHHockedFunction*)this;
	else *ppvObject = NULL;

	if (*ppvObject == NULL)
		return E_NOINTERFACE;
	
	AddRef ();
	return S_OK;
}

ULONG STDMETHODCALLTYPE CFunctionHook::AddRef( void)
{
	return InterlockedIncrement (&m_RefCount);
}

ULONG STDMETHODCALLTYPE CFunctionHook::Release( void)
{
	LONG result = InterlockedDecrement (&m_RefCount);

	if (result == 0)
		delete this;

	return result;
}

BOOL STDMETHODCALLTYPE CFunctionHook::IsHooked ()
{
	return m_IsHooked;
}

FARPROC STDMETHODCALLTYPE CFunctionHook::GetProc ()
{
	return m_PatchProc;
}

const std::wstring& CFunctionHook::GetModuleName () const
{
	return m_strModule;
}

const std::string& CFunctionHook::GetProcName () const
{
	return m_strProc;
}

void CFunctionHook::HookFunction ()
{
	m_IsHooked = false;

	if (m_OrgProc == NULL)
		return;

	DWORD OldFlags;
	DWORD Temp;

	DWORD SourceCodeSize;
	DWORD TargetCodeSize;

	bool Error = false;

	if (m_rHost.VirtualProtect (m_OrgProc, 64, PAGE_EXECUTE_READWRITE, &OldFlags))
	{
		if (CalculateCopySize (SourceCodeSize, TargetCodeSize))
		{
			m_OrginalCodeSize = SourceCodeSize;
			m_pOriginalCode = new BYTE[m_OrginalCodeSize];
			memcpy (m_pOriginalCode, m_OrgProc, m_OrginalCodeSize);

			if (!RedirectCall (m_OrgProc, m_TargetProc))
				Error = true;
		}
		else
			Error = true;

		
		m_rHost.VirtualProtect (m_OrgProc, 64, OldFlags, &Temp);
	}
	else
		Error = true;

	if (Error)
		return;

	m_PatchProc = m_rHost.GetPatchFunctionBlock ();

	if (m_rHost.VirtualProtect (m_PatchProc, 64, PAGE_EXECUTE_READWRITE, &OldFlags))
	{
		CopyCode (m_pOriginalCode, (BYTE*)m_PatchProc);

		m_rHost.VirtualProtect (m_PatchProc, 64, OldFlags, &Temp);
	}

	m_IsHooked = true;
}

bool CFunctionHook::CalculateCopySize (DWORD& rOrgSize, DWORD& rNeedSize)
{
  BYTE* proc = (BYTE*)m_OrgProc;

  rOrgSize = 0;
  rNeedSize = 0;

  CASMInstruction instruction;

  while (rOrgSize < PatchSize)
  {
    if (!instruction.Parse (&proc[rOrgSize]))
      return false;

    rOrgSize += instruction.GetSize ();

    rNeedSize += instruction.GetSize () + instruction.GetJumpPatchSize();

    if (instruction.IsStop())
      break;
  }

  rNeedSize += PatchSize;

  if (rOrgSize < PatchSize)
  {
//    LogMessage (ML_Alarm, "Need more Bytes");
    return false;
  }

  return true;
}

bool CFunctionHook::RedirectCall (FARPROC Org, FARPROC Dest)
{
  int DestAddr = *(int*)&Dest;
  int SrcAddr = *(int*)&Org;
  int Offset = DestAddr-SrcAddr-5;

  BYTE* pCode = (BYTE*)Org;
  pCode[0] = 0xE9; // JMP
  memcpy (&pCode[1], &Offset, 4);

  return true;
}

bool CFunctionHook::CopyCode (BYTE* pSourceCode, BYTE* pDestCode)
{
  DWORD SrcPos = 0;
  DWORD DestPos = 0;

  CASMInstruction instruction;

  while (SrcPos < PatchSize)
  {
    if (!instruction.Parse (&pSourceCode[SrcPos]))
      return false;

    instruction.Transfer (&pSourceCode[SrcPos], &pDestCode[DestPos]);

    SrcPos += instruction.GetSize ();
    DestPos += instruction.GetSize () + instruction.GetJumpPatchSize();

    if (instruction.IsStop())
      break;
  }

  int Offset = (((BYTE*)m_OrgProc)+SrcPos)-(pDestCode+DestPos)-5;

  pDestCode[DestPos++] = 0xe9; // JMP
  memcpy (&pDestCode[DestPos], &Offset, 4);

  return true;
}

void CFunctionHook::UnhookFunction ()
{
	if (m_IsHooked == false)
		return;

	DWORD OldFlags;
	DWORD Temp;

	if (m_rHost.VirtualProtect (m_OrgProc, 64, PAGE_EXECUTE_READWRITE, &OldFlags))
	{
		memcpy ((BYTE*)m_OrgProc, m_pOriginalCode, m_OrginalCodeSize);

		m_rHost.VirtualProtect (m_OrgProc, 64, OldFlags, &Temp);
	}

	delete [] m_pOriginalCode;
	m_pOriginalCode = NULL;
	m_OrginalCodeSize = 0;

	m_IsHooked = false;
}

void CFunctionHook::UpdateState (HMODULE hModule, FARPROC proc)
{
	if (m_hModule == hModule && m_OrgProc == proc)
		return;

	m_hModule = hModule;
	m_OrgProc = proc;

	if (m_OrgProc == NULL)
	{
		delete [] m_pOriginalCode;
		m_pOriginalCode = NULL;
		m_OrginalCodeSize = 0;
		m_IsHooked = false;
	}
	else
		HookFunction ();
}
